<?php
namespace App\Api\Controllers\Weixin;

use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Api\Controllers\Config\HuiPayConfigController;
use App\Api\Controllers\BaseController;
use App\Models\WeixinStore;
use App\Models\CustomerAppletsCoupons;
use App\Models\CustomerAppletsCouponUsers;

class WxCashCouponController extends BaseController
{
    /**
     * 微信代金券列表
     */
    public function wxCashCouponList(Request $request)
    {
        // 接收参数
        $input = $request->all();
        $page = $input['p'] ?? 1;
        $limit = $input['l'] ?? 10;
        $start = abs(($page - 1) * $limit);

        // 参数校验
        $check_data = [
            'store_id' => '门店号',
        ];
        $check = $this->check_required($input, $check_data);
        if ($check) {
            return $this->sys_response(40000, $check);
        }

        $date = date('Y-m-d H:i:s', time());

        $model = new CustomerAppletsCoupons();
        $list = [];
        $count = $model->getCashCouponCount($input);
        if ($count > 0) {
            $list = $model->getStoreCashCouponPageList($input, $start, $limit);
            foreach ($list as $k => $v) {
                if ($v['coupon_stock_type'] == 'NORMAL') {
                    $list[$k]['coupon_stock_type_name'] = '满减券';
                }
                if ($v['status'] == 1) {
                    $list[$k]['coupon_status'] = '审核中';
                } else if ($v['status'] == 3) {
                    $list[$k]['coupon_status'] = '审核不通过';
                } else {
                    if ($v['available_end_time'] < $date) {
                        $list[$k]['coupon_status'] = '已过期';
                    } else {
                        $list[$k]['coupon_status'] = '运行中';
                    }
                }

                $list[$k]['channel'] = '官方';
                $list[$k]['used_percent'] = ($v['used_num'] / $v['max_coupons']) * 100 . '%';
            }
        }

        return $this->sys_response_layui(1, '请求成功', $list, $count);
    }

    /**
     * 微信代金券批次详情
     */
    public function wxCashCouponStocksDetail(Request $request)
    {
        $input = $request->all();
        $page = $input['p'] ?? 1;
        $limit = $input['l'] ?? 10;
        $start = abs(($page - 1) * $limit);

        // 参数校验
        $checkData = [
            'store_id' => '门店号',
            'stock_id' => '批次号'
        ];
        $check = $this->check_required($input, $checkData);
        if ($check) {
            return $this->sys_response(40000, $check);
        }

        $customerAppletsCouponUsersModel = new customerappletsCouponUsers();

        // 用户领用代金券数量
        $userCouponCount = $customerAppletsCouponUsersModel->getUserGetCashCouponCount($input);

        $userCouponPageList = [];
        $date_now = date('Y-m-d H:i:s', time());
        if ($userCouponCount > 0) {
            // 获取微信代金券领用、核销分页列表（用户）
            $userCouponPageList = $customerAppletsCouponUsersModel->getUserGetCashCouponPageList($input, $start, $limit);
            foreach ($userCouponPageList as $k => $v) {
                $userCouponPageList[$k]['past_coupon_num'] = 0;
                if ($v['available_end_time'] < $date_now) {
                    $userCouponPageList[$k]['past_num'] += 1;
                }
            }
        }

        return $this->sys_response_layui(1, '请求成功', $userCouponPageList, $userCouponCount);
    }

    /**
     * 微信代金券批次使用、核销数量
     */
    public function wxCashCouponStocksCount(Request $request)
    {
        $input = $request->all();
        // 参数校验
        $checkData = [
            'store_id' => '门店号',
            'stock_id' => '批次号'
        ];
        $check = $this->check_required($input, $checkData);
        if ($check) {
            return $this->sys_response(40000, $check);
        }

        $customerAppletsCouponsModel = new CustomerAppletsCoupons();

        // 微信代金券领用、核销数量、总数量
        $totalCount = $customerAppletsCouponsModel->getCashCouponDetailCount($input);
        if (!empty($totalCount['max_coupons'])) {
            $totalCount['total_sent_num_percent'] = ($totalCount['total_sent_num'] / $totalCount['max_coupons']) * 100 . '%';
            $totalCount['total_used_num_percent'] = ($totalCount['total_used_num'] / $totalCount['max_coupons']) * 100 . '%';
        }

        return $this->sys_response_layui(1, '请求成功', $totalCount);
    }

    /**
     * 微信代金券核销明细列表
     */
    public function wxCashCouponUsedPageList(Request $request)
    {
        $input = $request->all();
        $page = $input['p'] ?? 1;
        $limit = $input['l'] ?? 10;
        $start = abs(($page - 1) * $limit);

        // 参数校验
        $checkData = [
            'store_id' => '门店号'
        ];
        $check = $this->check_required($input, $checkData);
        if ($check) {
            return $this->sys_response(40000, $check);
        }

        $model = new customerappletsCouponUsers();
        $weixinStore = new WeixinStore();

        // 查询此门店商户号
        $weixinStoreInfo = $weixinStore->where('store_id', $input['store_id'])->first();
        $input['wx_sub_merchant_id'] = $weixinStoreInfo->wx_sub_merchant_id;

        $count = $model->getCashCouponUsedCount($input);
        $list = [];
        if ($count > 0) {
            $list = $model->getCashCouponUsedPageList($input, $start, $limit);
            foreach ($list as $k => $v) {
                switch ($v['status']) {
                    case 'SENDED':
                        $list[$k]['status_name'] = '可用';
                        break;
                    case 'USED':
                        $list[$k]['status_name'] = '已使用';
                        break;
                    case 'EXPIRED':
                        $list[$k]['status_name'] = '已过期';
                        break;
                    default :
                        break;
                }
            }
        }

        return $this->sys_response_layui(1, '请求成功', $list, $count);
    }

    /**
     * 微信代金券扫二维码领券
     */
    public function oauth(Request $request)
    {
        $input = $request->all();
        // 参数校验
        $check_data = [
            'appid'                 => '公众账号ID',
            'stock_id'              => '批次号',
            'out_request_no'        => '商户单据号',
            'stock_creator_mchid'   => '创建批次的商户号',
        ];
        $check = $this->check_required($input, $check_data);
        if ($check) {
            return $this->sys_response(40000, $check);
        }

        $app_id = 'wx69adc3683ef01a09';
        $secret = '5bf171ff82be9d867b249581c2071ae7';

        $sub_info = [
            'appid'                 => $app_id,
            'stock_id'              => $input['stock_id'],
            'out_request_no'        => $input['out_request_no'],
            'stock_creator_mchid'   => $input['stock_creator_mchid'],
        ];

        $config = [
            'app_id' => $app_id,
            'scope' => 'snsapi_base',
            'oauth' => [
                'scopes'        => ['snsapi_base'],
                'response_type' => 'code',
                'callback'      => url('api/wechat/call_back?sub_info=' . $sub_info . '&wx_AppId=' . $app_id . '&wx_Secret=' . $secret . ''),
            ],
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;

        return $oauth->redirect();
    }

    /**
     * 微信扫码回调
     * @param Request $request
     */
    public function oauth_callback(Request $request)
    {
        // 接收参数
        $input      = $request->all();
        // 授权码
        $code       = $request->get('code');
        $wx_AppId   = $request->get('wx_AppId');
        $wx_Secret  = $request->get('wx_Secret');

        // 微信配置参数
        $config = [
            'app_id'        => $wx_AppId,
            "secret"        => $wx_Secret,
            "code"          => $code,
            "grant_type"    => "authorization_code",
        ];

        $app        = Factory::officialAccount($config);
        $oauth      = $app->oauth;
        $user       = $oauth->user();
        $open_id    = $user->getId();

        if (empty($open_id)) {
            return $this->sys_response(202, '领取失败');
        }


    }

    /**
     * 生成请求参数中用到的参数项out_request_no
     * @return string
     */
    public function getOutRequestNo(){
        return $this->merchantId.date("Ymd",time()).rand(10000,99999);
    }

    // 创建免充值微信代金券（商户创建）
    public function createMerchantCoupon(Request $request)
    {
        $requestData = $request->all();
        // 参数校验
        $check_data = [
            'store_id'                  => '门店id',
            'coupon_stock_name'         => '代金券名称',
            'transaction_minimum'       => '门槛',
            'discount_amount'           => '优惠金额',
            'available_begin_time'      => '使用开始时间',
            'available_end_time'        => '使用结束时间',
            'max_coupons'               => '发券数量',
            'max_coupons_per_user'      => '单人可领',
        ];
        $check = $this->check_required($requestData, $check_data);
        if ($check) {
            return $this->sys_response(40000, $check);
        }

        if ($requestData['discount_amount'] > $requestData['transaction_minimum']) {
            return $this->sys_response(40001, '优惠金额不可大于门槛金额');
        }
        if ($requestData['available_end_time'] < $requestData['available_begin_time']) {
            return $this->sys_response(40002, '结束时间不可小于开始时间');
        }
        if ($requestData['max_coupons_per_user'] > $requestData['max_coupons']) {
            return $this->sys_response(40003, '单人可领数量不可大于发券数量');
        }

        // 查询微信通道商户号
        $wechatStoreObj = WeixinStore::where('store_id', $requestData['store_id'])->first();
        if (empty($wechatStoreObj)) {
            return $this->sys_response_layui(4000, '微信通道商户号未配置');
        } else {
            $wx_sub_merchant_id = $wechatStoreObj->wx_sub_merchant_id;
        }

        // 插入数据
        $insertData = [
            'coupon_type'               => 2,
            'coupon_source'             => 1,
            'use_method'                => 1,
            'coupon_code_mode'          => 'WECHATPAY_MODE',
            'coupon_stock_type'         => 'NORMAL',
            'consume_mchid'             => $wx_sub_merchant_id,
            'store_id'                  => $requestData['store_id'],
            'coupon_belong_merchant'    => $requestData['coupon_belong_merchant'] ?? 1,
            'coupon_stock_name'         => $requestData['coupon_stock_name'],
            'transaction_minimum'       => $requestData['transaction_minimum'],
            'discount_amount'           => $requestData['discount_amount'],
            'available_begin_time'      => $requestData['available_begin_time'],
            'available_end_time'        => $requestData['available_end_time'],
            'max_coupons'               => $requestData['max_coupons'],
            'max_coupons_per_user'      => $requestData['max_coupons_per_user'],
            'max_amount'                => $requestData['max_coupons'] * $requestData['discount_amount'],
            'created_at'                => date('Y-m-d H:i:s', time()),
            'updated_at'                => date('Y-m-d H:i:s', time()),
        ];

        $model = new CustomerAppletsCoupons();
        $insert_res = $model->insertData($insertData);
        if ($insert_res) {
            return $this->sys_response_layui(1, '操作成功');
        } else {
            return $this->sys_response_layui(4000, '操作失败');
        }
    }

}
